package com.wyp168.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName RomanToInt
 * @Description TODO
 * @Author wyp168
 * @Date 2022/7/2 11:00
 */
public class RomanToInt {
    public static void main(String[] args) {

        //测试
        String s = "MCMXCIV";
        System.out.println(romanToInt(s));

    }
    /*
    字符          数值
    I             1
    V             5
    X             10
    L             50
    C             100
    D             500
    M             1000
     */
    public static int romanToInt(String s) {
        Map<String,Integer> roman = new HashMap<>();

        //将对应的罗马字符放进map集合中，便于后面操作
        roman.put("I",1);
        roman.put("V",5);
        roman.put("X",10);
        roman.put("L",50);
        roman.put("C",100);
        roman.put("D",500);
        roman.put("M",1000);

        //封装返回结果
        int res = 0;
        //处理入参
        for (int i = 0; i < s.length(); i++) {
            String subS = s.substring(i, i + 1);
            if (i < s.length() - 1) {
                String subSNext = s.substring(i + 1, i + 2);
                if (roman.get(subS) < roman.get(subSNext)) {
                    res += (roman.get(subSNext) - roman.get(subS));
                    i ++;
                    continue;
                } else {
                    res += roman.get(subS);
                    continue;
                }
            }
            res += roman.get(subS);


        }
        return res;
    }
}
